package com.wzw.shoppingcart.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzw.shoppingcart.entity.Discount;
import com.wzw.shoppingcart.service.DiscountService;
import com.wzw.shoppingcart.vo.Result;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;


/**
 *@author wzw
 * 2023/4/8
 */
@RestController
@RequestMapping("/discount")
@Setter(onMethod_ = {@Autowired})
public class DiscountController {

    private  DiscountService discountService;

    @GetMapping("/list")
    public Result<Page<Discount>> getDiscounts(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            String keyword) {
        QueryWrapper<Discount> queryWrapper = Wrappers.query();
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like("discount_name", keyword);
        }
        Page<Discount> discountPage = discountService.page(new Page<>(pageNum, pageSize),queryWrapper);
        return Result.success(discountPage);
    }

    @GetMapping("/id")
    public Discount getDiscountById(@RequestParam("id") Integer id) {
        return discountService.getById(id);
    }

    @PostMapping
    public boolean saveDiscount(@RequestBody Discount discount) {
        return discountService.save(discount);
    }

    @DeleteMapping
    public boolean deleteDiscountByIds(@RequestBody Integer[] ids) {

        return discountService.removeBatchByIds(Arrays.asList(ids));
    }

    @PutMapping
    public boolean updateDisCount(@RequestBody Discount disCount) {

        UpdateWrapper<Discount> wrapper = new UpdateWrapper<>();
        wrapper.eq("discount_id", disCount.getDiscountId());
        return discountService.update(disCount, wrapper);
    }
}
